;;; Ejemplo de uso de sockets. 
;;; Script cliente.
(ns utilities.cliente
(:gen-class))
(use 'clojure.contrib.duck-streams)

(import '(java.net Socket ServerSocket)
        '(java.io PrintWriter)
	'(java.io File FileInputStream RandomAccessFile)
	'(java.util Scanner))

(def *port* 3003)
(def r "114")
(def i "105")

(defn peticiona
	"Ask the server for the database"
	[ip]
  (let [newfileserver (File. "/tempserver.db")
  	  newfileclient (File. "/tempclient.db")
  	  socket (Socket. ip *port*)]
  	  (with-open [input (.getInputStream socket)
  	  	  output (PrintWriter. (.getOutputStream socket))
                fileserver (RandomAccessFile. (.getName newfileserver) "rw")
                fileclient (RandomAccessFile. (.getName newfileclient) "rw")]
                (.println output "p")
                (.flush output)
      (loop []
        (let [c (.read input)]
          (when (not= c -1)
          	  (.write fileserver c)
          	  (.write fileclient c)
            (recur)))))))
 
(defn comparedbs
	"Compares if the 2 databases are equal"
	[socket]
	(let [newclientserver (File. "/clientserver.db")]
	(with-open [output-2 (.getOutputStream socket)
		input (.getInputStream socket)
		clientserver (RandomAccessFile. (.getName newclientserver) "rw")
		rfcontentclient (FileInputStream. (File. "tempclient.db"))]
		(loop []
			(let [c (.read input)]
				(when (not= c -1)
					(.write clientserver c)
					(recur))))
		(let [contentclientserver (slurp "clientserver.db")
			contenido (slurp "tempserver.db")]
			(if (.equals contenido contentclientserver)
				1 
				2))
)))
   (defn sendact
   	   "Sends the request to compare the databases"
	[ip]
	(let [socket (Socket. ip *port*)]
		(with-open [output (PrintWriter. (.getOutputStream socket))]
			(.println output "s")
			(.flush output)
			(comparedbs socket)
			
				
)))
			
						
(defn sendnew
	"Sends the updated database"
	[ip]
	(let [socket (Socket. ip *port*)]
		(with-open [output (PrintWriter. (.getOutputStream socket))
			output-2 (.getOutputStream socket)
		rfcontentclient (FileInputStream. (File. "tempclient.db"))]
		(.println output "n")
                (.flush output)
		(let [buff (byte-array 1024)]
			(loop [reed (.read rfcontentclient buff)]
				(if (> reed 0)
					(do
						(.write output-2 buff, 0, reed)
						(recur (.read rfcontentclient buff))))))
)))

			
			
